package database

import (
	"context"
	"fmt"
	"gitee.com/sdzxq/api_server/models"
	"github.com/mongodb/mongo-go-driver/bson"
	"github.com/mongodb/mongo-go-driver/mongo"
	"github.com/mongodb/mongo-go-driver/x/bsonx"
)

func TestDbConnect() bool {
	err = DbClient.Ping(context.TODO(), nil)
	if err != nil {
		fmt.Println(err)
		return false
	}
	return true
}


func CreateUser(newUser models.User) (bool, error) {
	collection := DbClient.Database("mainzxq").Collection("user" )
	res, err := collection.InsertOne(context.TODO(), newUser)
	if err != nil {
		fmt.Println("this is api error!")
		return false, err
	}
	fmt.Println("Insert one doc by ID:", res.InsertedID)
	return true, nil
}


func FindOneUser(uid string) (*models.User, error) {
	var result models.User
	collection := DbClient.Database("mainzxq").Collection("user")
	err := collection.FindOne(context.TODO(),bson.D{{"userid",uid}}).Decode(&result)
	if err != nil {
		return  nil, err
	}
	fmt.Println(result)
	return &result, nil
}

func CreateIndex(keyname string) {
	collection := DbClient.Database("mainzxq").Collection("user")
	iv := collection.Indexes()
	name, err := iv.CreateOne(context.Background(), mongo.IndexModel{
		// 指定用作索引的键名和排序方案
		Keys: bsonx.Doc{{keyname,bsonx.Int32(-1)}},
		Options: mongo.NewIndexOptionsBuilder().Name("yes").Build(),
	})
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(name)
}
